import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-10
 * Time: 9:09
 */
public class UdpEchoClient1 {
    DatagramSocket socket = null;
    String serverIP;
    int serverPort;

    public UdpEchoClient1(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("->");
            //1、从控制台输入请求
            if(!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();
            //2、把字符串请求构造成数据报，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            //3、接收服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //4、把响应转换成字符串,把响应内容显示到控制台上
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient1 udpEchoClient1 = new UdpEchoClient1("127.0.0.1", 9090);
        udpEchoClient1.start();
    }
}
